/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, {Component} from 'react';
import {
    StyleSheet,
    Text,
    View,
    AsyncStorage,
    ScrollView,
    Image,
    DeviceEventEmitter,
    ListView,
    TouchableOpacity,
    Alert, NativeModules,
} from 'react-native';

import Navigation from "../../custom/Navigation";
import StyleUtils from "../../res/styles/StyleUtils";
import ViewUtils from "../../utils/ViewUtils";
import SlideMenu from "../../menu/SlideMenu";
import AlertDialog from "../../custom/AlertDialog";
import I18n from "../../res/language/i18n";
import ModalListUtils from "../../utils/ModalListUtils";
import CommonUtils from "../../common/CommonUtils";
import IparNetwork from "../../httpUtils/IparNetwork";

let languageData = [
    {name: I18n.t('default.english'), code: 'en'},
    {name: I18n.t('default.russian'), code: 'ru'},
    {name: I18n.t('default.chines'), code: 'zh'},
    // {name: I18n.t('default.uyghur'), code: 'uy'},
];
export default class SettingsPage extends Component {

    constructor(props) {
        super(props);

        let ds = new ListView.DataSource({
            rowHasChanged: (r1, r2) => r1 !== r2,
        });
        this.state = {
            showAlert: false,
            alertType: -1,//0是退出登录/1是注销账号
            languageVisible: false,
            languageData: ds.cloneWithRows(languageData),
            lang_s: I18n.t('default.english'),
            country: null,
        };


    }

    componentDidMount() {

        CommonUtils.getAcyncInfo('userInfo')
            .then((result) => {
                this.userInfo = JSON.parse(result);
            });


        CommonUtils.getAcyncInfo('country')
            .then((result) => {
                this.setState({country: result})
            })

        /**
         * 获取用户以前设置的语言
         */
        switch (I18n.locale) {
            case 'en':
                this.setState({lang_s: I18n.t('default.english')});
                break;
            case 'ru':
                this.setState({lang_s: I18n.t('default.russian')});
                break;
            case 'zh':
                this.setState({lang_s: I18n.t('default.chines')});
                break;
            case 'uy':
                this.setState({lang_s: I18n.t('default.uyghur')});
                break;

        }


        this.iparNetwork = new IparNetwork();
    }


    render() {
        const {alertType} = this.state;
        return (
            <View style={StyleUtils.flex}>
                <Navigation
                    onClickLeftBtn={() => {
                        this.props.navigator.pop()
                    }}
                    leftButtonIcon={require('../../res/images/ic_back.png')}
                    titleImage={require('../../res/images/ic_ipar_logo.png')}

                />
                <ScrollView>
                    <View style={[StyleUtils.flex, {padding: 16}]}>
                        {ViewUtils.getTitleView(I18n.t('default.settings'), I18n.t('default.settingsNote'))}
                        <View style={StyleUtils.lineStyle}/>
                        {ViewUtils.gitUserInformationTv(I18n.t('default.country'), this.state.country)}

                        <Text style={[StyleUtils.smallFont, {
                            marginTop: 16,
                            fontSize: 18,
                            color: 'black',
                            textAlign: 'left'
                        }]}>{I18n.t('default.SerLang')}</Text>

                        <View style={[StyleUtils.justifySpace]}>
                            <Text style={[StyleUtils.smallFont, {
                                flex: 1,
                                textAlign: 'left',
                            }]}>{this.state.lang_s}</Text>

                            <TouchableOpacity
                                style={{padding: 10}}
                                onPress={() => this.setState({languageVisible: true,})}>
                                <Text style={[StyleUtils.smallFont, {
                                    textAlign: 'right',
                                }]}>{I18n.t('default.edit')}</Text>
                            </TouchableOpacity>
                        </View>
                        {/*<Text style={[StyleUtils.smallFont, {*/}
                        {/*marginTop: 24,*/}
                        {/*fontSize: 18,*/}
                        {/*color: 'black',*/}
                        {/*textAlign: 'left'*/}
                        {/*}]}>{I18n.t('default.receNotifi')}</Text>*/}
                        {/*<Text style={[StyleUtils.smallFont, {*/}
                        {/*marginTop: 16,*/}
                        {/*textAlign: 'left'*/}
                        {/*}]}>{I18n.t('default.edit')}</Text>*/}


                        {ViewUtils.getButton(I18n.t('default.logout'), () => {
                            this.setState({
                                showAlert: true,
                                alertType: 0,
                            })
                        }, {marginTop: 30})}

                    </View>
                </ScrollView>

                <View style={[{padding: 16,}, StyleUtils.center]}>

                    <TouchableOpacity
                        onPress={() => {
                            this.setState({
                                showAlert: true,
                                alertType: 1,
                            })
                        }}
                        style={[{
                            borderWidth: 1,
                            borderRadius: 4,
                            borderColor: '#dddddd',
                            paddingHorizontal: 16,
                            paddingVertical: 8
                        }]}>
                        <Text style={[{fontSize: 14, color: '#828282'}]}>{I18n.t('alert.unsubscribeAccount')}</Text>
                    </TouchableOpacity>
                </View>
                <ModalListUtils
                    close={() => {
                        this.setState({
                            languageVisible: false
                        })
                    }}
                    onPress={(index, text) => this.editLanguage(languageData[index])}
                    dataParam={'name'}
                    visible={this.state.languageVisible}
                    dataSource={this.state.languageData}
                />

                <AlertDialog
                    requestClose={() => {
                        this.setState({
                            showAlert: false,
                        })
                    }}
                    leftBtnOnclick={() => {
                        this.setState({
                            showAlert: false,
                        });
                        if (alertType === 1)
                            this.unsubscribeAccount();
                        else
                            this.logout()
                    }}
                    contentTv={alertType === 1 ? I18n.t('alert.unsubscribeAccountMsj') : I18n.t('default.logoutContent')}
                    visible={this.state.showAlert}/>


            </View>)


    }

    /**
     * 手该语言
     */
    editLanguage(data) {
        this.setState({
            languageVisible: false,
        });
        I18n.locale = data.code;

        this.setState({lang_s: data.name});

        AsyncStorage.setItem('lang', data.code, (error, result) => {
        })
    }


    /**
     * 重新打开home页面
     */
    startHome() {
        this.props.navigator.resetTo({
            component: SlideMenu,
        })
    }


    /**
     * 注销账号
     */
    unsubscribeAccount() {
        CommonUtils.showLoading();

        this.iparNetwork.getRequest()
            .then((result) => {
                CommonUtils.dismissLoading();
                this.logout();
            })
            .catch((er) => {
                CommonUtils.dismissLoading();
                DeviceEventEmitter.emit('toast', I18n.t('default.fail'))
            });
    }

    /**
     * 退出登陆
     */
    logout() {
        if (this.userInfo)
            NativeModules.UMPushModule.deleteAlias(this.userInfo.main_user_id, 'IPAR_SHOP_ID', (code) => {
            });

        AsyncStorage.removeItem('userInfo', (error, result) => {
            this.startHome()
        });
    }

}


